<?php

class Application_Model_Coupon extends Application_Model_DomainObject {

    protected $_id;
    protected $_dateCreated; //创建日期
    protected $_no; //优惠券号
    protected $_type; // 
    protected $_money; //需要达到的金额,0为不限
    protected $_scope;
    protected $_discount;  //折扣金额
    protected $_startTime; //开始时间
    protected $_dateExpired; //过期时间
    protected $_status; //状态  1.有效  2.己使用  -1.过期
    protected $_useTime; //使用时间
    protected $_relevance; //关联操作的ID
    protected $_userType; //用户类型
    protected $_password; //密码,如为空则不需要难密码
    protected $_userId; //用户ID
    protected $_name; //优惠券名称
    protected $_batchNo;
    protected $_common; //备注

    /**
     * 可用 
     */

    const STATUS_OK = 1;

    /**
     * 已用
     */
    const STATUS_USED = 2;

    /**
     * 已过期
     */
    const STATUS_EXPIRED = -1;

    /**
     * 验证优惠券是否可用
     * @param type $userId 用户ID
     * @param type $money 用户的订单金额
     * @param type $password 密码,如无需要则不传
     */
    public function isValid($userId, $money, $password) {
        if ($this->_status != Application_Model_Coupon::STATUS_OK)
            return FALSE;

        if ($this->_userId != $userId)
            return FALSE;

        if ($this->_dateExpired < time())
            return FALSE;

        if ($this->_password != NULL && $this->_password != '' && $this->_password == $password)
            return FALSE;

        if ($this->_money > $money)
            return FALSE;

        return TRUE;
    }

    /**
     * 验证优惠券
     * @param type $userId
     * @param type $money
     * @param type $password 
     * @return Application_Model_CouponResult
     */
    public function Validate($userId, $money, $password) {
        $validator = $this->getValidator();
        return $validator->Validate($userId, $money, $password);
    }

    /**
     * 返回验证器
     * @return type 
     */
    private function getValidator() {
        return Application_Model_Coupons_CouponBase::createCoupon($this);
    }

    /**
     * 根据优惠券号返回一张优惠券
     * @param type $no
     * @return Application_Model_Coupon
     */
    public static function getByNo($no) {
        $db = Application_Model_Coupon::getDao();
        return $db->queryOne(array('no' => $no));
    }

    public function gettypeName() {
        switch ($this->type) {
            case 1:
                return "通用型优惠券";
            default :
                return "抵用券";
        }
    }

    public function getuserTypeName() {
        switch ($this->userType) {
            case 0:
                return "代购";
            default :
                return "代购";
        }
    }

    private static function getDb() {
        return new Application_Model_DbTable_Coupon();
    }

    /*
     * 根据用户名，状态获取当前记录总数
     * @param int $userid 用户序号
     * @param int $state 用户序号
     * @return int
     */

    public static function getItemCount($userid, $state) {

        $bill = new Application_Model_DbTable_Coupon();

        return $bill->getItemCount($userid, $state);
    }

    /**
     * 根据用户ID,返回指定状态的优惠券
     * @param type $userId 用户ID
     * @param type $status 状态
     * @return array 
     */
    public static function getByUser($userId, $status) {
        return Application_Model_Coupon::getDb()->queryAll(array('userId' => $userId, 'status' => $status));
    }

    public static function getCountByStatus($userId, $status, $starttime = '', $endtime = '') {
        if ($starttime == '' || $endtime == '')
            $where = array('userId' => $userId, 'status' => $status);
        else
            $where = array('userId' => $userId, 'status' => $status, ' and dateExpired<=' => $starttime, ' and dateExpired<=' => $endtime);

        return Application_Model_Coupon::getDb()->count($where);
    }
    
    public static function getByWayId($wayId){
        return self::getDao()->queryAll(array('relevance'=>  $wayId));
    }

    /**
     * 返回优惠券名称 
     */
    public function getTitle() {
        return $this->getValidator()->getTitle();
    }

    public function getDiscountMoney() {
        return $this->_discount;
    }

    /**
     * 
     * @param int $inid
     * @param int $memberId
     * @param date $startTime 开始时间
     * @param date $endTime 结束时间
     * @param int $status 状态
     * @param int $count
     * @param int $offset
     * @return 返回格式为 array('size'=>?,'list'=>?,'pages'=>?,'index'=>?) 
     * size为查询记录的总条数，list为返回的array型数据，pages是指有多少页，index为当前是哪一页 
     */
    public static function getByFilter($inid, $memberId, $startTime, $endTime, $status, $count, $offset) {
        $where = array();
        $and = '';


        if ($memberId != NULL) {
            $where[$and . ' userId = '] = $memberId;
            $and = ' and ';
        }

        if ($status != NULL) {
            $where[$and . ' status = '] = $status;
            $and = ' and ';
        }

        if ($startTime != NULL) {
            $where[$and . ' dateCreated >= '] = $startTime;
            $and = ' and ';
        }

        if ($endTime != NULL) {
            $where[$and . ' dateCreated <= '] = $endTime;
            $and = ' and ';
        }

        return Application_Model_Coupon::getDb()->queryPage($where, 'dateExpired desc ', $count, $offset);
    }

    /**
     * 根据用户ID和批次号获取用户的优惠券
     * @param type $userId
     * @param type $batchNo 
     */
    public static function search($userId, $batchNo) {
        return Application_Model_Coupon::getDao()->queryAll(array('userId' => $userId, 'batchNo' => $batchNo));
    }

    public static function getByNewFilter($no, $storeno, $startTime, $dateExpired, $batchNo, $status, $pagesize, $pageindex) {
        $where = array();
        $and = '';

        if ($no != NULL) {
            $where[$and . ' no = '] = $no;
            $and = ' and ';
        }

        if ($storeno != NULL) {
            $uwhere[' storeno = '] = $storeno;
            $userItem = Application_Model_User::bystore($storeno);
            if ($userItem) {
                $where[$and . ' userId = '] = $userItem->id;
                $and = ' and ';
            } else {
                return null;
            }
        }

        if ($status != NULL) {
            $where[$and . ' status = '] = $status;
            $and = ' and ';
        }
        if ($batchNo != NULL) {
            $where[$and . ' batchNo = '] = $batchNo;
            $and = ' and ';
        }
        if ($startTime != NULL) {
            $where[$and . ' startTime >= '] = $startTime;
            $and = ' and ';
        }

        if ($dateExpired != NULL) {
            $where[$and . ' dateExpired <= '] = $dateExpired;
            $and = ' and ';
        }
        return Application_Model_Coupon::getDao()->queryPage($where, 'dateExpired desc ', $pagesize, $pageindex);
    }

    /**
     * 返回用户信息
     */
    public function getuser() {
        return Application_Model_User::load($this->_userId);
    }

    public function getscopeName() {
        switch ($this->_scope) {
            case 0:
                return "所有";
            case 1:
                return "运单";
            case 2:
                return "代购";
            default :
                return "所有";
        }
    }

    public function getstatusName() {
        switch ($this->status) {
            case 1:
                return "未使用";
            case 2:
                return "已使用";
            case 3:
                return "已过期";
            default :
                return "未知状态";
        }
    }

    public static function getisno($no) {
        $where[' no = '] = $no;
        return Application_Model_Coupon::getDao()->queryOne($where);
    }

    public static function addcoupon($userId, $no, $arrup) {
        $couponItem = Application_Model_Coupon::getisno($no);
        if ($couponItem) {
            return 22;
        } else {
            if ($arrup["batchNo"] != "通用") {
                $batchItem = Application_Model_Coupon::getcountcoupon($userId, $arrup["batchNo"]);
                if ($batchItem != 0) {
                    return 33;
                }
            }
        }
        $couponObj = new Application_Model_Coupon();
        foreach ($arrup as $key => $val) {
            $couponObj->$key = $val;
        }
        $couponObj->dateCreated = date("Y-m-d H:i:s");
        $couponObj->status = 1;
        $couponObj->save();
        Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_addcoupon, $couponObj->no, $couponObj->userId);
        $couponBatch = Application_Model_CouponBatch::getByNo($arrup["batchNo"]);
        $couponBatch->giveCount = $couponBatch->giveCount + 1;
        $couponBatch->save();
        return 1;
    }

    public static function getcountcoupon($userId, $batchNo) {
        $where[' userId = '] = $userId;
        $where[' and batchNo = '] = $batchNo;
        return Application_Model_Coupon::getDao()->count($where);
    }

    public static function byrelevance($id) {
        $where[" relevance = "] = $id;
        return Application_Model_Coupon::getDao()->queryOne($where);
    }

}